<template>
  <div class="settings-container">
    <el-card class="filter-card">
      <div slot="header" class="clearfix">
        <!-- 导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
         <el-col :span="16">
            <el-form ref="user" :model="user" label-width="80px" :rules="formRules">
              <el-form-item label="编号">
                {{user.id}}
              </el-form-item>
              <el-form-item label="手机">
                {{user.mobile}}
              </el-form-item>
              <el-form-item label="媒体名称" prop="name">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="媒体介绍" prop="intro">
                <el-input type="textarea" v-model="user.intro"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onUpDateUser" :loading="updateLoading">保存</el-button>
              </el-form-item>
            </el-form>
         </el-col>
         <el-col :span="4" :offset="2">
          <label for="file"><el-avatar shape="square" :size="150" fit="cover" :src="user.photo"></el-avatar></label>
          <input type="file" id="file" hidden ref="file" @change="fileUp">
         </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="修改头像"
      width="40%"
      :visible.sync="dialogVisible"
      @opened="onDialogOpend"
      @closed="onDialogclose"
      >
      <div class="avatar-desc" >
        <img :src="avatar" alt="" ref="avatar" class="avatar" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"  @click="onUpCropperImage">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, UserAvatar, UserProfile } from '@/api/user.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import globalBus from '@/utils/global-bus'
export default {
  name: 'SettingsIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        id: null,
        mobile: '',
        name: '',
        intro: '',
        email: '',
        photo: ''
      },
      dialogVisible: false,
      avatar: '', // 预览图片
      cropper: null, // 裁切器实例
      updateLoading: false,
      formRules: {
        name: [
          {
            required: true, message: '请输入媒体名称', trigger: 'blur'
          },
          {
            min: 1, max: 7, message: '长度为1-7个字符', trigger: 'blur'
          }
        ],
        intro: [
          {
            required: true, message: '请输入媒体介绍', trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadUser()
  },
  mounted () {},
  methods: {
    onUpDateUser () {
      this.$refs.user.validate((valid) => {
        console.log(valid)
        if (!valid) {
          // 验证失败
          return false
        } else {
          this.updateLoading = true
          UserProfile(this.user).then(res => {
            this.$message({
              type: 'success',
              message: '保存成功~'
            })
            // 关闭loading状态
            this.updateLoading = false
            // 发布通知用户已修改
            globalBus.$emit('upadte-user', this.user)
          })
        }
      })
    },
    loadUser () {
      getUserProfile().then(res => {
        console.log(res)
        this.user = res.data.data
      })
    },
    fileUp () {
      const file = this.$refs.file
      const blobData = window.URL.createObjectURL(file.files[0])
      this.avatar = blobData
      this.dialogVisible = true
      // 解决选择相同文件不触发change事件问题
      this.$refs.file.value = ''
    },
    onDialogOpend () {
      // 图片裁切器必须基于img进行初始化
      // 注意：img必须是可见状态 ，才能完成初始化
      // 第一次初始化完成后，如果预览裁切的图片发生了变化，默认不会更新 replace/destroy
      const image = this.$refs.avatar // 获取图片DOM节点
      if (this.cropper) {
        this.cropper.replace(this.avatar) // 会闪一下bug
        return
      }
      this.cropper = new Cropper(image, {
        aspectRatio: 4 / 4, // 裁切器的比例
        viewMode: 1,
        dragMode: 'none',
        // cropBoxMovable: false,
        // cropBoxResizable: false,
        background: false,
        movable: true,
        // 移动裁切器的时候会触发 crop方法
        crop (event) {

        }
      })
    },
    onDialogclose () {
      // 对话框关闭，销毁裁切器
      // this.cropper.destroy() 性能消耗大
    },
    onUpCropperImage () {
      // 获取裁切的图片对象
      // 请求更新用户头像
      this.cropper.getCroppedCanvas().toBlob((file) => {
        const fd = new FormData()
        fd.append('photo', file)
        // 请求提交fd
        UserAvatar(fd).then(res => {
          console.log(res)

          this.dialogVisible = false
          // 更新视图展示 服务端返回图片进行展示有点慢
          // this.user.photo = res.data.data.photo

          // 直接把裁切结果的文件对象转为Blob数据本地预览
          this.user.photo = window.URL.createObjectURL(file)

          // 发布通知用户已修改
          globalBus.$emit('upadte-user', this.user)
        })
      })
    }
  }
}
</script>

<style scoped lang="less">
.avatar-desc{
  margin:0 auto;
  width: 500px;
}
 .avatar{
   display: block;
   height: auto;
   max-width: 100%;
 }
</style>
